<template>
  <div class="sys-section-bg">
    <div style="height:32px;"></div>
    <el-row :gutter="20" class="sys-stat-row">
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#409EFF" size="22"><i-ep-document /></el-icon>
            <div class="stat-info">
              <div class="stat-title">文章总数</div>
              <div class="stat-value">{{ articles.length }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#67C23A" size="22"><i-ep-document /></el-icon>
            <div class="stat-info">
              <div class="stat-title">已发布</div>
              <div class="stat-value">{{articles.filter(a => a.status === '已发布').length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#E6A23C" size="22"><i-ep-document /></el-icon>
            <div class="stat-info">
              <div class="stat-title">草稿</div>
              <div class="stat-value">{{articles.filter(a => a.status === '草稿').length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#F56C6C" size="22"><i-ep-document /></el-icon>
            <div class="stat-info">
              <div class="stat-title">分类数</div>
              <div class="stat-value">{{[...new Set(articles.map(a => a.category))].length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider content-position="left">文章列表</el-divider>
    <div class="page-title">
      <el-icon><i-ep-document /></el-icon>
      <span style="margin-left: 8px; font-size: 20px; font-weight: bold;">文章管理</span>
    </div>
    <div class="toolbar">
      <el-input v-model="articleSearch" placeholder="请输入文章标题/作者/分类/标签" style="width: 240px; margin-right: 16px;" clearable />
      <el-button type="primary" @click="handleArticleSearch">搜索</el-button>
      <el-button type="success" @click="openAddArticleDialog" style="margin-left: 16px;">添加文章</el-button>
    </div>
    <el-table :data="pagedArticles" style="width: 100%; margin-top: 16px;" v-loading="articleLoading">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="category" label="分类" />
      <el-table-column prop="tags" label="标签" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '已发布' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openEditArticleDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteArticle(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next, jumper" :total="filteredArticles.length" :page-size="articlePageSize" :current-page="articleCurrentPage" @current-change="handleArticlePageChange" style="margin-top: 16px; text-align: right;" />
    
    <!-- 添加/编辑文章弹窗 -->
    <el-dialog :title="articleDialogMode === 'add' ? '添加文章' : '编辑文章'" v-model="articleDialogVisible" width="600px" @close="resetArticleDialog">
      <el-form :model="articleDialogForm" :rules="articleDialogRules" ref="articleDialogFormRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleDialogForm.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="articleDialogForm.author" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="articleDialogForm.category" placeholder="请选择分类">
            <el-option label="技术" value="技术" />
            <el-option label="产品" value="产品" />
            <el-option label="设计" value="设计" />
            <el-option label="运营" value="运营" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="articleDialogForm.status" placeholder="请选择状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="articleDialogForm.content" type="textarea" :rows="6" placeholder="请输入文章内容" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="articleDialogForm.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="articleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitArticleDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 文章管理数据
const articles = ref([])
const articleSearch = ref('')
const articlePageSize = ref(10)
const articleCurrentPage = ref(1)
const articleDialogVisible = ref(false)
const articleDialogMode = ref('add')
const articleDialogForm = ref({ id: null, title: '', author: '', category: '', status: '草稿', content: '', tags: '' })
const articleDialogFormRef = ref(null)
const articleLoading = ref(false)
const articleDialogRules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  tags: [{ required: false, message: '请输入标签', trigger: 'blur' }]
}

const filteredArticles = computed(() => {
  return articles.value
})

const pagedArticles = computed(() => {
  const start = (articleCurrentPage.value - 1) * articlePageSize.value
  return filteredArticles.value.slice(start, start + articlePageSize.value)
})

// 获取文章数据（对接后端）
async function fetchArticles() {
  console.log('开始获取文章数据...')
  articleLoading.value = true
  try {
    const params = {
      page: articleCurrentPage.value,
      pageSize: articlePageSize.value
    }
    
    const res = await axios.get(getApiUrl('/article/list'), { params })
    
    if (res.data) {
      // 后端直接返回文章数组，需要映射字段格式
      const rawArticles = Array.isArray(res.data) ? res.data : []
      articles.value = rawArticles.map(article => ({
        id: article.id,
        title: article.title,
        author: article.createBy || '未知', // 后端没有author字段，使用createBy
        category: article.category,
        tags: article.tags,
        content: article.content,
        status: article.status === 1 ? '已发布' : article.status === 0 ? '草稿' : '下线',
        createTime: new Date(article.createdAt).toLocaleString('zh-CN'),
        createdAt: article.createdAt,
        updatedAt: article.updatedAt
      }))
      console.log('API返回文章数:', articles.value.length)
    } else {
      articles.value = []
      console.log('API返回数据为空或格式不正确')
    }
  } catch (e) {
    console.error('获取文章失败:', e)
    ElMessage.error('获取文章失败: ' + (e.response?.data || e.message))
    articles.value = []
  }
  articleLoading.value = false
  console.log('获取文章数据完成，当前文章数量:', articles.value.length)
}

// 创建文章
async function createArticle(articleData) {
  try {
    // 将前端状态值转换为后端状态值
    const statusMap = {
      '草稿': 0,
      '已发布': 1,
      '下线': 2
    }
    
    const res = await axios.post(getApiUrl('/article/create'), {
      title: articleData.title,
      content: articleData.content,
      category: articleData.category,
      tags: articleData.tags || '',
      status: statusMap[articleData.status] || 0  // 添加状态字段
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('创建文章响应:', res)
    
    // 成功时返回的是数据本身，不是ApiResult
    if (res.data.success) {
      ElMessage.success('添加成功')
      return res.data.data // 返回创建的文章数据
    } else {
      ElMessage.error(res.data.message || '创建失败')
      return false
    }
  } catch (e) {
    console.error('创建文章失败:', e)
    ElMessage.error('创建文章失败: ' + (e.response?.data?.msg || e.message))
    return false
  }
}

// 更新文章
async function updateArticle(articleData) {
  try {
    // 将前端状态值转换为后端状态值
    const statusMap = {
      '草稿': 0,
      '已发布': 1,
      '下线': 2
    }
    
    const res = await axios.put(getApiUrl(`/article/update/${articleData.id}`), {
      title: articleData.title,
      content: articleData.content,
      category: articleData.category,
      tags: articleData.tags || '',
      status: statusMap[articleData.status] || 0  // 添加状态字段
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('更新文章响应:', res)
    
    // 成功时返回的是数据本身，不是ApiResult
    if (res.data.success) {
      ElMessage.success('编辑成功')
      return res.data.data // 返回更新的文章数据
    } else {
      ElMessage.error(res.data.message || '更新失败')
      return false
    }
  } catch (e) {
    console.error('更新文章失败:', e)
    ElMessage.error('更新文章失败: ' + (e.response?.data?.msg || e.message))
    return false
  }
}

// 删除文章
async function deleteArticle(articleId) {
  console.log('调用删除API，文章ID:', articleId, '类型:', typeof articleId)
  console.log('当前文章列表:', articles.value.map(a => ({ id: a.id, title: a.title, idType: typeof a.id })))
  
  try {
    const res = await axios.delete(getApiUrl(`/article/delete/${articleId}`), {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('删除API响应:', res)
    
    // 成功时返回204 No Content状态码
    if (res.data.success) {
      // 从列表中移除文章 - 使用字符串比较确保类型匹配
      const idx = articles.value.findIndex(a => String(a.id) === String(articleId))
      console.log('找到的文章索引:', idx, '要删除的ID:', articleId)
      
      if (idx !== -1) {
        articles.value.splice(idx, 1)
        console.log('删除成功，剩余文章数量:', articles.value.length)
      } else {
        console.log('未找到要删除的文章，ID:', articleId)
      }
      
      ElMessage.success('删除成功')
      console.log('删除成功')
      return true
    } else {
      ElMessage.error(res.data.message || '删除失败')
      console.log('删除失败')
      return false
    }
  } catch (e) {
    console.error('删除文章失败:', e)
    ElMessage.error('删除文章失败: ' + (e.response?.data?.msg || e.message))
    return false
  }
}

// 搜索文章
async function searchArticles(searchData) {
  try {
    const res = await axios.post(getApiUrl('/article/search'), {
      title: searchData.title || null,
      category: searchData.category || null,
      tags: searchData.tags || null
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (res.data) {
      articles.value = res.data.articles || []
      // Assuming total is part of the response or needs to be fetched separately
      // For now, we'll just log the total if available
      console.log('API返回总文章数:', res.data.total)
    }
  } catch (e) {
    console.error('搜索文章失败:', e)
    ElMessage.error('搜索文章失败: ' + (e.response?.data?.message || e.message))
  }
}

async function handleArticleSearch() {
  articleCurrentPage.value = 1
  if (articleSearch.value.trim()) {
    // 尝试按标题、作者、分类或标签搜索
    await searchArticles({
      title: articleSearch.value,
      category: null,
      tags: null
    })
  } else {
    await fetchArticles()
  }
}

function openAddArticleDialog() {
  articleDialogMode.value = 'add'
  Object.assign(articleDialogForm.value, { id: null, title: '', author: '', category: '', status: '草稿', content: '', tags: '' })
  articleDialogVisible.value = true
  nextTick(() => articleDialogFormRef.value && articleDialogFormRef.value.clearValidate())
}

function openEditArticleDialog(row) {
  articleDialogMode.value = 'edit'
  // 将后端数据格式转换为前端表单格式
  Object.assign(articleDialogForm.value, {
    id: row.id,
    title: row.title,
    author: row.author,
    category: row.category,
    status: row.status, // 已经是前端格式（'草稿'/'已发布'）
    content: row.content,
    tags: row.tags
  })
  articleDialogVisible.value = true
  nextTick(() => articleDialogFormRef.value && articleDialogFormRef.value.clearValidate())
}

function resetArticleDialog() {
  Object.assign(articleDialogForm.value, { id: null, title: '', author: '', category: '', status: '草稿', content: '', tags: '' })
}

async function submitArticleDialog() {
  articleDialogFormRef.value.validate(async valid => {
    if (!valid) return
    
    try {
      let result = false
      
      if (articleDialogMode.value === 'add') {
        result = await createArticle(articleDialogForm.value)
        if (result) {
          // 添加成功后，将新文章添加到本地数组
          articles.value.unshift(result)
          articleDialogVisible.value = false
        }
      } else {
        result = await updateArticle(articleDialogForm.value)
        if (result) {
          // 更新成功后，直接更新本地数据
          const index = articles.value.findIndex(a => a.id === articleDialogForm.value.id)
          if (index !== -1) {
            articles.value[index] = result
          }
          articleDialogVisible.value = false
        }
      }
    } catch (error) {
      console.error('提交失败:', error)
    }
  })
}

async function handleDeleteArticle(row) {
  try {
    await ElMessageBox.confirm(`确定要删除文章 ${row.title} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    console.log('开始删除文章:', row.id)
    const success = await deleteArticle(row.id)
    console.log('删除结果:', success)
    
    if (success) {
      console.log('删除成功，当前文章数量:', articles.value.length)
      
      // 若当前页无数据，自动跳到上一页
      nextTick(() => {
        console.log('检查分页:', pagedArticles.value.length, articleCurrentPage.value)
        if (pagedArticles.value.length === 0 && articleCurrentPage.value > 1) {
          articleCurrentPage.value--
          console.log('跳转到上一页:', articleCurrentPage.value)
        }
      })
    }
  } catch (error) {
    // 用户取消删除
    console.log('用户取消删除')
  }
}

function handleArticlePageChange(page) {
  articleCurrentPage.value = page
}

// 组件挂载时获取数据
onMounted(() => {
  fetchArticles()
})
</script>

<style scoped>
.sys-section-bg {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.sys-stat-row {
  margin-bottom: 24px;
}

.sys-stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.sys-stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #333;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
</style> 